package com.kaoyaya.delivery.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.ViewById;
import com.kaoyaya.delivery.activity.R;
import com.kaoyaya.delivery.activity.SearchActivity_;
import com.kaoyaya.delivery.activity.SlidingActivity;
import com.kaoyaya.delivery.adapter.ComboAdapter;
import com.kaoyaya.delivery.data.Constants;
import com.kaoyaya.delivery.data.DataHelper;
import com.kaoyaya.delivery.data.entity.Combo;
import com.kaoyaya.delivery.data.entity.OrderItem;
import com.kaoyaya.util.CommUtil;
import com.kaoyaya.util.StringUtil;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

@EFragment(R.layout.fmt_combo)
public class ComboFmt  extends Fragment  {
	
	@ViewById LinearLayout llArea;
	@ViewById ImageView ivSearch;
	@ViewById TextView tvNum, tvCity;
	@ViewById ExpandableListView elvCombo;
	@ViewById RelativeLayout rlSearchLeft;
	@Bean DataHelper dataHelper;
	PopupWindow window;
	ComboAdapter comboAdapter;
	SlidingActivity activity;
	Dialog pgDialog;
	final int IS_COMBO_LIST = 0, IS_COMBO_SEARCH = 22, IS_AREA = 2;
	
	// 更多布局
	LinearLayout llMore;
	ProgressBar pbMore;
	TextView tvMore;
	boolean hasMore, isCity;
	int lastIndex, count, pageIndex;
	String area, name, lowest, highest;
	String[] areas;
	
	@AfterViews
	void initView() {
		this.activity = (SlidingActivity) getActivity();
		initCartNum();
		llArea.setVisibility(View.GONE);
		View vMore = LayoutInflater.from(activity).inflate(R.layout.more_data_bar, null);
		llMore = (LinearLayout) vMore.findViewById(R.id.llMore);
		llMore.setVisibility(View.GONE);
		pbMore = (ProgressBar) vMore.findViewById(R.id.pbMore);
		tvMore = (TextView) vMore.findViewById(R.id.tvMore);
		llMore.setOnClickListener(clickListener);
		elvCombo.addFooterView(vMore);
		elvCombo.setOnScrollListener(scrollListener);
		dataHelper.setCallbackHandler(callbackHandler);
		//dataHelper.getAreas(IS_AREA);
		if (Constants.authGlobal || Constants.authCombo) {
			initCombo();
		}
	}
	
	void initCartNum() {
		if (Constants.cart.size() != 0) {
			tvNum.setVisibility(View.VISIBLE);
			tvNum.setText(String.valueOf(Constants.cart.size()));
			activity.updateCart();
		} else {
			tvNum.setVisibility(View.GONE);
		}
	}
	
	void initCombo() {
		llMore.setVisibility(View.GONE);
		pgDialog = CommUtil.createLoadingDialog(activity, null);
		lastIndex = 0; count = 0; pageIndex = 0;
		if (isCity) {
			name = null; lowest = null; highest = null;
		}
		comboAdapter = null;
		dataHelper.getCombos(IS_COMBO_LIST, pageIndex, area, name, lowest, highest);
	}
	
	void nextPageProducts() {
		if (hasMore) {
			pbMore.setVisibility(View.VISIBLE);
			tvMore.setText("数据正在加载，请稍候...");
			pageIndex++;
			dataHelper.getCombos(IS_COMBO_LIST, pageIndex, area, name, lowest, highest);
		}
	}
	
	View.OnClickListener clickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.llMore:
				nextPageProducts();
				break;
			case R.id.btnBuy:
				Combo combo = (Combo) v.getTag();
				OrderItem orderItem = new OrderItem();
				orderItem.setNo(combo.getId());
				orderItem.setType(1);
				orderItem.setCount(1);
				orderItem.setPrice(combo.getPrice());
				orderItem.setName(combo.getName());
				Constants.cart.add(orderItem);
				initCartNum();
				break;
			default:
				break;
			}
		}
	};
	
	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			lastIndex = firstVisibleItem + visibleItemCount - 1;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (hasMore && lastIndex == comboAdapter.getGroupCount() && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
				nextPageProducts();
			}
		}
		
	};
	
	@Click
	void rlSearchLeft() {
		activity.showLeft();
	}
	
	@Click
	void llArea() {
		createPopWindow(areas);
	}
	
	@Click
	void ivSearch() {
		startActivityForResult(new Intent(getActivity(), SearchActivity_.class), IS_COMBO_SEARCH);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null && requestCode == IS_COMBO_SEARCH) {
			name = data.getStringExtra("name");
			lowest = data.getStringExtra("lowest");
			highest = data.getStringExtra("highest");
			isCity = false;
			initCombo();
		}
	}
	
	@SuppressWarnings("unchecked")
	Handler callbackHandler = new Handler() {
		public void handleMessage(Message msg) {
			Object result = msg.obj;
			if (result != null) {
				switch (msg.what) {
				case IS_COMBO_LIST:
					if (comboAdapter == null) {
						comboAdapter = new ComboAdapter(getActivity(), clickListener, new ArrayList<Combo>());
						elvCombo.setAdapter(comboAdapter);
					}
					List<Combo> combos = (List<Combo>) result;
					int size = combos.size();
					count += size;
					comboAdapter.addCombo(combos);
					comboAdapter.notifyDataSetChanged();
					hasMore = size < Constants.PAGE_COMBO_SIZE ? false : true;
					if (count > 0) {
						tvMore.setText(hasMore ? "加载更多..." : "总共" + count + "个套餐");
						pbMore.setVisibility(View.GONE);
						llMore.setVisibility(View.VISIBLE);
					} else {
						Toast.makeText(activity, "没有获取到对应的数据!", Toast.LENGTH_SHORT).show();
					}
					break;
				case IS_AREA:
					String[] temp = (String[]) result;
					areas = new String[1 + temp.length];
					areas[0] = "全部";
					for (int i = 0; i < temp.length; i++) {
						areas[i + 1] = temp[i];
					}
					break;
				}
			}
			if (pgDialog != null) {
				pgDialog.cancel();
			}
		}
	};
	
	private void createPopWindow(String[] areas) {
		if (areas!=null) {
			List<Map<String, String>> areaMaps = new ArrayList<Map<String,String>>();
			for (String area : areas) {
				Map<String, String> itemArea = new HashMap<String, String>();
				itemArea.put("area", area);
				areaMaps.add(itemArea);
			}
			View vPopArea = LayoutInflater.from(activity).inflate(R.layout.pop_area, null);
			ListView lvArea = (ListView) vPopArea.findViewById(R.id.lvArea);
			lvArea.setAdapter(new SimpleAdapter(activity, areaMaps, R.layout.item_pop, new String[]{"area"}, new int[]{R.id.tvName}));
			lvArea.setOnItemClickListener(itemClickListener);
			window = new PopupWindow(vPopArea, llArea.getWidth() * 2, LayoutParams.WRAP_CONTENT);
			window.setBackgroundDrawable(activity.getResources().getDrawable(R.color.transparent));
			window.setFocusable(true);
			window.setOutsideTouchable(true);
			int[] cityLocation = new int[2];
			int[] searchLocation = new int[2];
			tvCity.getLocationOnScreen(cityLocation);
			rlSearchLeft.getLocationOnScreen(searchLocation);
			window.showAtLocation(tvCity, Gravity.NO_GRAVITY, cityLocation[0], searchLocation[1] + rlSearchLeft.getHeight());
		}
	}
	
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			window.dismiss();
			Map<String, String> item = (Map<String, String>) arg0.getItemAtPosition(arg2);
			area = item.get("area");
			tvCity.setText(area);
			if (StringUtil.isNotTrimBlank(area) && "全部".equals(area)) {
				area = null;
			}
			isCity = true;
			initCombo();
		}
		
	};
	
}
